Tuesday, April 05, 2005

3 steps to Late binding in VB.Net and C#

This is a code snippet showing how to achieve late binding in both Vb.Net and C# .

Step One :
Create a Dll called Calc.dll which has a class named MyClass.
Add a function called "Add" which adds two number and returns the result. The implementaion for it is as follows :

namespace Calc
{
public class MyClass
{
public MyClass()
{
}
public int Add (int i , int j)
{
return i+j; // adds the two numbers and returns the result
}
}
}


Step Two :

Create a Vb.Net project (may be Windows Application project) which can use the above Dll.
Add reference to the above Dll.
Add a button to the form and type and code as shown below

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim oMyClass As Object
oMyClass = New Calc.MyClass
MessageBox.Show(oMyClass.Add(1, 2))
End Sub

Please take not that in the above code.The Type of "oMyClass" object is Object and NOT Calc. But the complier will still complie this code. (Check the intellisense for oMyClass object and the you will not see the Add method instead you will see the default methods of type Sysem.Object)


Step Three :

Create a C#.Net project (may be Windows Application project).
Dont add reference to the above Dll.
Add two buttons to the form and type and code as shown below:

Button 1:

Assembly oAssembly = Assembly.LoadFrom("Calc.dll");
Type[] oTypes = oAssembly.GetTypes();

foreach(Type oTempType in oTypes)
{
MethodInfo[] mi = oTempType.GetMethods(BindingFlags.DeclaredOnly|BindingFlags.Public|BindingFlags.Instance );
Object oLateBoundObject = Activator.CreateInstance(oTempType);
MessageBox.Show(mi[0].Invoke(oLateBoundObject,new object[]{1,2}).ToString()); // Calling the Add Method
}

Please take a note that the way C# handles late biding is completely different and is based on Reflection.

Button 2:

/*
THIS CODE WILL NOT COMPILE

Object oMyClass = new Object();
oMyClass = new DLLProj.MyClass();
MessageBox.Show(oMyClass.Add(1, 2).ToString());

*/

Well if we try to do it the way we did in VB.Net it will simply just not compile. Uncomment the code for Button 2 and check it out for urself.


With Best Regards,
Mitesh V. Mehta

1 Comments:

Blogger morris said...

This article gives the light in which we can observe the reality. This is very nice one and gives indepth information. Thanks for this nice article. read

March 12, 2021 at 5:13 AM  

Post a Comment

<< Home